import { login, logout, refreshToken, phoneLogin } from '@/api/system/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { getInfo } from '@/api/system/auth'

const state = {
  token: getToken(),
  name: '',
  avatar: '/avatar/default-avatar.gif',
  introduction: '',
  roles: [],
  menus: [],
  permissions: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { token } = response
        commit('SET_TOKEN', token)
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 手机号验证码登录
  phoneLogin({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      phoneLogin({ phone: userInfo.phone, code: userInfo.code }).then(response => {
        const { token } = response
        commit('SET_TOKEN', token)
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // token 失效后重新登录
  refreshToken({ commit }) {
    return new Promise((resolve, reject) => {
      refreshToken().then(res => {
        commit('SET_TOKEN', res.token)
        // setToken(res.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { menus, permissions } = response
        if (!response) {
          reject('Verification failed, please Login again.')
        }

        // roles must be a non-empty array fix: 修改按menu_codes作为roles
        if (!menus || menus.length <= 0) {
          reject('权限不足')
        }

        commit('SET_ROLES', menus) // 后端返回菜单栏CODE作为菜单栏权限判断
        commit('SET_NAME', response.name ?? 'Admin')
        commit('SET_AVATAR', '/avatar/default-avatar.gif')
        commit('SET_INTRODUCTION', '')
        commit('SET_MENUS', menus)
        commit('SET_PERMISSIONS', permissions)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_NAME', '')
        commit('SET_AVATAR', '')
        commit('SET_TOKEN', '')
        commit('SET_INTRODUCTION', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        commit('SET_MENUS', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_MENUS', [])
      commit('SET_PERMISSIONS', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    // setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
